﻿using System;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.IO;
using Gueei.Gallery.Core.Entities;

namespace Gueei.Gallery.Core.DisplayProfiles
{
	public class DisplayProfile:DisplayProfileBase
	{
		public virtual int MaxWidth { get; set; }
		public virtual int MaxHeight { get; set; }
		public virtual bool MaintainRatio { get; set; }
		public virtual bool ResizeIfSmaller { get; set; }

		public override byte[] ConvertImage(byte[] original, string mime)
		{
			System.Drawing.Image imgToResize = System.Drawing.Image.FromStream(
				new MemoryStream(original)
				);

			int sourceWidth = imgToResize.Width;
			int sourceHeight = imgToResize.Height;

			float nPercent = 0;
			float nPercentW = 0;
			float nPercentH = 0;

			nPercentW = ((float)MaxWidth / (float)sourceWidth);
			nPercentH = ((float)MaxHeight / (float)sourceHeight);

			nPercent = nPercentH < nPercentW ? nPercentH : nPercentW;

			if ((nPercent >= 1) && !ResizeIfSmaller) return original;

			var destWidth = (int)(sourceWidth * nPercent);
			var destHeight = (int)(sourceHeight * nPercent);

			var b = new Bitmap(destWidth, destHeight);
			Graphics g = Graphics.FromImage((System.Drawing.Image)b);
			g.InterpolationMode = InterpolationMode.HighQualityBicubic;

			g.DrawImage(imgToResize, 0, 0, destWidth, destHeight);
			g.Dispose();

			var ms = new MemoryStream();
			b.Save(ms, GetImageFormatFromMime(mime));
			return ms.ToArray();
		}

		protected System.Drawing.Imaging.ImageFormat GetImageFormatFromMime(string mime)
		{
			switch(mime)
			{
				case "image/jpeg":
					return System.Drawing.Imaging.ImageFormat.Jpeg;
				case "image/png":
					return System.Drawing.Imaging.ImageFormat.Png;
				case "image/gif":
					return System.Drawing.Imaging.ImageFormat.Gif;
				default:
					throw new ArgumentException();
			}
		}
	}
}
